﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AvalonDock;
using tiDE.Support;
using System.Net;
using System.Xml.Linq;

namespace tiDE.Panels
{
    /// <summary>
    /// Interaction logic for StartPage.xaml
    /// </summary>
    public partial class StartPage : DockableContent
    {
        public event EventHandler NewProjectClicked;
        public event EventHandler<OpenProjectEventArgs> OpenProjectRequested;

        public StartPage()
        {
            InitializeComponent();

            FeedItems = new List<StartPageFeedItem>();
            foreach (string feed in SettingsProvider.GetInstance().StartPageFeedProviders)
            {
                WebClient client = new WebClient();
                client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
                client.OpenReadAsync(new Uri(feed));
            }
        }

        int numErrors = 0, numItems = 0;
        List<StartPageFeedItem> FeedItems;

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            numItems++;
            NewsFeedLoadingText.Visibility = System.Windows.Visibility.Collapsed;
            if (e.Error != null)
            {
                numErrors++;
                if (numErrors == SettingsProvider.GetInstance().StartPageFeedProviders.Count)
                    Dispatcher.BeginInvoke((Action)(() => ErrorLoadingFeedsPanel.Visibility = System.Windows.Visibility.Visible));
                return;
            }
            XDocument doc = XDocument.Load(e.Result);
            try
            {
                XElement channel = doc.Root.Element("channel");
                string title = channel.Element("title").Value;
                Uri imageUri = null;
                try
                {
                    imageUri = new Uri(channel.Element("image").Element("url").Value);
                } catch { }

                foreach (XElement item in channel.Elements("item"))
                {
                    StartPageFeedItem feedItem = new StartPageFeedItem();
                    feedItem.ImageSource = imageUri;
                    feedItem.PublishTime = DateTime.Parse(item.Element("pubDate").Value);
                    feedItem.FeedTitle = title + " - " + feedItem.PublishTime.ToShortDateString();
                    feedItem.ItemTitle = item.Element("title").Value;
                    feedItem.ItemSnippet = HTMLStripper.StripTagsCharArray(WebUtility.HtmlDecode(item.Element("description").Value));
                    feedItem.ItemLink = item.Element("link").Value;
                    FeedItems.Add(feedItem);
                }
            }
            catch
            {
                numErrors++;
                if (numErrors == SettingsProvider.GetInstance().StartPageFeedProviders.Count)
                    Dispatcher.BeginInvoke((Action)(() => ErrorLoadingFeedsPanel.Visibility = System.Windows.Visibility.Visible));
                return;
            }
            if (numItems == SettingsProvider.GetInstance().StartPageFeedProviders.Count)
            {
                FeedItems = new List<StartPageFeedItem>(FeedItems.OrderByDescending(item => item.PublishTime));
                Dispatcher.BeginInvoke((Action)(() => NewsFeedListBox.ItemsSource = FeedItems));
            }
        }

        private void Border_MouseEnter(object sender, MouseEventArgs e)
        {
            (sender as Border).BorderBrush = new SolidColorBrush(Colors.Gray);
        }

        private void Border_MouseLeave(object sender, MouseEventArgs e)
        {
            (sender as Border).BorderBrush = new SolidColorBrush(Colors.Transparent);
        }

        private void Border_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            System.Diagnostics.Process.Start(((sender as Border).DataContext as StartPageFeedItem).ItemLink);
        }

        private void NewProjectButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("New project pressed");
        }

        private void OpenProjectButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("Open project pressed");
        }

        private void NewsFeedListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            NewsFeedListBox.SelectedIndex = -1;
        }
    }

    class StartPageFeedItem : IComparable
    {
        public string FeedTitle { get; set; }
        public string ItemTitle { get; set; }
        public string ItemLink { get; set; }
        public Uri ImageSource { get; set; }
        public string ItemSnippet { get; set; }
        public DateTime PublishTime { get; set; }

        public int CompareTo(object obj)
        {
            return PublishTime.CompareTo(((StartPageFeedItem)(obj)).PublishTime);
        }
    }

    public class OpenProjectEventArgs : EventArgs
    {
        public string ProjectFile { get; set; }

        public OpenProjectEventArgs(string ProjectFile)
        {
            this.ProjectFile = ProjectFile;
        }
    }
}
